<?php 
class coupons
{
	var $db;
	function coupons()
	{
		global $db;	
		$this -> db     = & $db;
	}
	//添加优惠券
	function add_coupons()
	{
		$sql="INSERT INTO ".COUPONS." (`title` ,`desc` ,`cpns_if` , `start_time` ,`end_time` ,`cpns_then` ,`create_time` ,`status`,`type`,`catid`,`except`,`per_type`,`cost_points`,`cpns_event_key`,`cpns_platform`,`cpns_stock` )VALUES ( '$_POST[title]','$_POST[desc]', '$_POST[cpns_if]','".$_POST['stime']."','".$_POST['etime']."', '$_POST[cpns_then]','".time()."','$_POST[status]','$_POST[type]','$_POST[catid]','$_POST[except]','$_POST[per_type]','$_POST[cost_points]','$_POST[cpns_event_key]','$_POST[cpns_platform]','$_POST[cpns_stock]')";
		$this->db->query($sql);
	}
	//修改优惠券
	function edit_coupons()
	{
		$sql="UPDATE ".COUPONS."  SET `title` = '$_POST[title]',`desc` = '$_POST[desc]',`cpns_if` = '$_POST[cpns_if]',`start_time` =  '".$_POST['stime']."',`end_time` = '".$_POST['etime']."',`cpns_then` = '$_POST[cpns_then]',`status` = '$_POST[status]' ,`type`='$_POST[type]',`catid`='$_POST[catid]',`except`='$_POST[except]',`per_type`='$_POST[per_type]',`cost_points`='$_POST[cost_points]',`cpns_event_key`= '$_POST[cpns_event_key]',`cpns_platform`= '$_POST[cpns_platform]',`cpns_stock`= '$_POST[cpns_stock]' WHERE `id` ='$_POST[id]'  ";	
		$this->db->query($sql);
	}
	//获取所有优惠券列表
	function get_coupons_list()
	{
		$sql="select id,title,start_time,end_time,cpns_if,cpns_then from ".COUPONS." where status>0 ";
		$page = new Page;
		$page->listRows=20;
		if (!$page->__get('totalRows')){
			$this->db->query($sql);
			$page->totalRows =$this->db->num_rows();
		}
		$sql .= "  limit ".$page->firstRow.",20";
		//=====================
		$this->db->query($sql);
		$re['list']=$this->db->getRows();
		$re['page']=$page->prompt();	
		return $re;
	}
	//生成优惠券密码
	function get_coupons_pwd($num,$type=0,$cpns_id,$make_type,$cpns_make_nums=0){//make_type=long长 15位 short 短8位
	    $str="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
			switch ($type){
				case 0:
					$prefix= 'C';
					break;
				case 1:
					$prefix ='H';
					break;
				case 2:
					$prefix ='U';
					break;
				case 3:
					$prefix ='T';
					break;
				case 4:
					$prefix ='M';
					break;
			  case 5:
					$prefix ='S';
				  break;
			}
			if ($make_type!='short'){
			    $make_type='long';
			}
			if ($make_type=='short'){
			    $prefix.=str_pad(substr($cpns_id, -2),2,'0',STR_PAD_LEFT);
			}else{
			    $prefix.=str_pad(substr($cpns_id, -3).$str[$cpns_make_nums%32],4,'0',STR_PAD_LEFT);
			}	
	    
	    $rands_long=$make_type=='short'?5:10;
	    for($j=0;$j<$num;$j++)
	    {
	    $password='';
	    for($i=0;$i<$rands_long;$i++){
	        $password.=$str[rand(0,31)];
	    }
	    $password=$prefix.$password;
	    
	    $pwd[]=$password;
	    }
	    
	    return array_unique($pwd);
	    
	}
	
	//生成优惠券
	function make_coupons(&$cpns,$pwds){
	    $sql="INSERT INTO ".COUPONSUSERS." (`title` ,`desc` ,`cpns_if` , `start_time` ,`end_time` ,`cpns_then` ,`make_time` ,`status`,`type`,`catid`,`except`,`cpns_key` ,`cpns_id`,`per_type`)VALUES";
	    
	    $values=array();
	    foreach ($pwds as $item){
	        $values[]="( '$cpns[title]','$cpns[desc]', '$cpns[cpns_if]','$cpns[start_time]','$cpns[end_time]', '$cpns[cpns_then]','".time()."','0','$cpns[type]','$cpns[catid]','$cpns[except]','$item','$cpns[id]','$cpns[per_type]')";
	    }
	    $sql.=implode(',', $values);
	    
	    $this->db->query($sql);
	    $nums=count($pwds);
	    $sql="UPDATE ".COUPONS."  SET `cpns_nums` = `cpns_nums`+$nums,`cpns_make_nums`=`cpns_make_nums`+1 where id='$cpns[id]'";
	    $this->db->query($sql);
	    return true;
	    
	}
	
	//发放
	function send_coupons($id,$cpns_id){
	    
	    if (is_array($id)){
	        $nums=count($id);
	        $where='id in('.implode(',', $id).')';
	    }else{
	        $nums=1;
	        $where="id='$id'";
	    }
	    $sql="update ".COUPONSUSERS." set status=1,send_time='".time()."'  where $where";
	    $this->db->query($sql);
	    $sql="UPDATE ".COUPONS."  SET `cpns_sends` = `cpns_sends`+$nums where id='$cpns_id'";
	    $this->db->query($sql);
	    return true;
	}
	//禁用
	function forbid_coupons($id,$cpns_id){
	     
	    if (is_array($id)){
	        $nums=count($id);
	        $where='id in('.implode(',', $id).')';
	    }else{
	        $nums=1;
	        $where="id='$id'";
	    }
	    $sql="update ".COUPONSUSERS." set status=-1  where $where";
	    $this->db->query($sql);
	    return true;
	}
	//绑定
	function bind_coupons($keys,$buid='',$user=''){
	    
	   $cpns = $this->check_coupons($keys);
	   $t=time();
	   if (empty($cpns)||$cpns['status']<=0||$cpns['type']==0){
	       return '优惠券无效';
	   }elseif ($cpns['status']>=2){
	       return '优惠券已绑定或使用';
	   }elseif ($cpns['end_time']<$t){
	       return '优惠券已过期';
	   }
	   if(!$buid||!($user))
	   {
	       global $buid;
	       $user=$_COOKIE['USER'];
	       
	       if (!$buid){
	           return '用户不存在';
	       }
	   }
	   $sql="update ".COUPONSUSERS." set status=2,uid='$buid', uname='{$user}',bind_time='{$t}'  where id=$cpns[id]";
	   $this->db->query($sql);
	   $sql="UPDATE ".COUPONS."  SET `cpns_binds` = `cpns_binds`+1 where id='{$cpns['cpns_id']}'";
	   $this->db->query($sql);
	   return 1;
	}
	
	function use_coupons($cpns_id,$order_id){
	    global $buid;
	    $t=time();
	   if ($cpns=$this->check_cpns_info($cpns_id)){
	       if($cpns['type']==1){
	           $sql="update ".COUPONSUSERS." set status=3,use_time='{$t}',order_id='{$order_id}'";
	           if (empty($cpns['uid'])){
	               $sql.=",uid='$buid', uname='{$_COOKIE['USER']}'";
	           }
	           $sql.=" where id=$cpns[id]";
	           $this->db->query($sql);
	       }else{
	           $sql="insert into ".COUPONSUSERS." set status=3,use_time='{$t}',order_id='{$order_id}'";
	           foreach ($cpns as $key=>$item){
	               if (in_array($key, array('id','uname','uid','status','bind_time', 'send_time', 'use_time', 'make_time','order_id')))continue;
	               $sql.=", `$key`='$item'";
	           }
	           if (empty($cpns['uid'])){
	               $sql.=",uid='$buid', uname='{$_COOKIE['USER']}'";
	           }
	           $this->db->query($sql);
	       }
	       $sql="UPDATE ".COUPONS."  SET `cpns_used` = `cpns_used`+1 where id='{$cpns['cpns_id']}'";
	       $this->db->query($sql);
	   }
	   return 1;
	}
	
	
	
	function check_is_used(){//检测是否有可用的优惠券
	    global $buid;
	    $sql="select * from ".COUPONSUSERS." where  uid='{$buid}' and status=2 and end_time>".time(). " and start_time<".time();
	    $this->db->query($sql);
	    $cpns= $this->db->getRows();
	    return $cpns;
	}
	
	function check_cpns_info($cpns_id){//检测优惠券是否存在
	    global $buid;
	    if (is_numeric($cpns_id)){
	        $sql="select * from ".COUPONSUSERS." where  uid='{$buid}' and status=2 and id={$cpns_id} and end_time>".time(). " and start_time<".time(). " limit 1";
	        $this->db->query($sql);
	    }else{
	        $sql="select * from ".COUPONSUSERS." where  (type=1 and status>0 and status<3 or type=0 and status=1) and cpns_key='{$cpns_id}' and end_time>".time(). " and start_time<".time(). " limit 1";
	        $this->db->query($sql);
	    }
	    if ($cpns=$this->db->fetchRow()){
	        return $this->check_per_user_info($cpns);
	    }else{
	        return false;
	    }
	}
	
	function check_per_user_info(&$cpns){//检测单个人使用次数
	    global $buid;
	    if ($cpns['type']==1){//唯一不存在此情况
	        return $cpns;
	    }
	    $sql="select per_type from ".COUPONS." where id=$cpns[cpns_id] limit 1";
	    $this->db->query($sql);
	    $cpns_check_data=$this->db->fetchRow();
	    
	    if ($cpns_check_data['per_type']==0){
	        return $cpns;
	    }
	    $sql ="select count(*) as use_time from ".COUPONSUSERS." where uid='$buid' and cpns_key='$cpns[cpns_key]'";
	    $this->db->query($sql);
	    $use_time=$this->db->fetchRow();
	    if ($use_time['use_time']<$cpns_check_data['per_type']){
	        return $cpns;
	    }else{
	        return '-2';
	    }
	}
	
	
	function cpns_back_to($order_id){//订单取消 返回优惠券
	    $sql ="select *  from ".COUPONSUSERS." where order_id='$order_id' limit 1";
	    $this->db->query($sql);
	    if ($cpns=$this->db->fetchRow()){
	        if ($cpns['type']==0){//通用的直接删除
	            $this->db->query("delete from ".COUPONSUSERS." where id ='{$cpns['id']}'");
	            $sql="UPDATE ".COUPONS."  SET `cpns_used` = `cpns_used`-1 where id='{$cpns['cpns_id']}'";
	            $this->db->query($sql);
	        }elseif ($cpns['type']==1){
	            if ($cpns['bind_time']){//如果绑定过退回绑定状态
	                $sql="update ".COUPONSUSERS." set status=2,order_id='' where id='{$cpns['id']}'";
	                $this->db->query($sql);
	                
	            }else{
	                $sql="update ".COUPONSUSERS." set status=1,order_id='',uid='', uname='' where id='{$cpns['id']}'";//如果未绑定 恢复状态
	                $this->db->query($sql);
	            }
	            $sql="UPDATE ".COUPONS."  SET `cpns_used` = `cpns_used`-1 where id='{$cpns['cpns_id']}'";
	            $this->db->query($sql);
	        }
	    }
	}
	
	
	
	function check_coupons_in_cart(&$cart,$cpns){
	    $cat_price=array();
	    
	    $pro_list=array();//全部商品列表 
	    foreach ($cart['cart'] as $prolist){
	        foreach ($prolist['prolist'] as $pitem){//计算各个分类的价格追溯到根级别
	            if (!$pitem['catid'])continue;
	            //print_r($pitem);
	            $cat_price[$pitem['catid']]+=$pitem['price']*$pitem['num'];
	            
	            if(strlen($pitem['catid'])>6){
	                $cat_price[substr($pitem['catid'],0,6)]+=$pitem['price']*$pitem['num'];
	            }
	            if(strlen($pitem['catid'])>4){
	                $cat_price[substr($pitem['catid'],0,4)]+=$pitem['price']*$pitem['num'];
	            }
	            $pro_list[$pitem['pid']]=$pitem['price']*$pitem['num'];
	            
	        }
	    }
	    
	    //print_r($cat_price);
	    //print_r($pro_list);
	   
	    
	    $return_cpns=array();
	    foreach ($cpns as $item){
	    //总价不够，不可使用
	    if($cart['sumprice'] <$item['cpns_if']){continue;}
	    
	    if ($item['catid']){//带分类的情况
	           $cat_price_of_item=$cat_price[$item['catid']];
	           if ($cat_price_of_item<$item['cpns_if']){continue;}
	    }
	    if ($item['except']){//含特殊商品的情况
	        $except_item=explode(',', trim($item['except'],','));
	        $except_price=0;
	        foreach ($except_item as $ey_except_item){
	            $except_price+=$pro_list[$ey_except_item];
	        }
	        if ($cart['sumprice']-$except_price<$item['cpns_if']){continue;}
	    }
	    
	    $return_cpns[]=$item;
	    
	    }
	    return $return_cpns;
	}

	
	    
	private function check_coupons($keys){
	    $sql="select id,cpns_id,status,start_time,end_time,type  from ".COUPONSUSERS." where  cpns_key='{$keys}' limit 1";
	    $this->db->query($sql);
	    $cpns= $this->db->fetchRow();
	    return $cpns;
	}
}
?>